package org.hy.common.utils;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author hy
 * @version 1.0
 * @date 2020-09-22 9:26
 */
public final class FileUtils {

    private FileUtils(){
        throw new AssertionError("no instance for you.");
    }

    public static void copy(File source, File target) throws IOException{
        if(source != null && target != null && !target.isDirectory()){
            final Path targetFilePath = Paths.get(target.getPath());
            final Path targetFilePathParent = targetFilePath.getParent();
            if(!Files.exists(targetFilePathParent)){
                Files.createDirectories(targetFilePathParent);
            }
            if(!Files.exists(targetFilePath)){
                Files.createFile(targetFilePath);
            }
            try(FileOutputStream fos = new FileOutputStream(target)){
                copy(source, fos);
            }
        }
    }

    public static void copy(File source, OutputStream outputStream) throws IOException{
        try(FileInputStream fis = new FileInputStream(source);
            FileChannel fileChannel = fis.getChannel();
            BufferedOutputStream bos = new BufferedOutputStream(outputStream);
            final WritableByteChannel writableByteChannel = Channels.newChannel(bos)){
            fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);
        }
    }

    public static void createFile(byte[] bytes, String filePth, String fileName) throws IOException{
        final Path filePath = Paths.get(filePth, fileName);
        final Path parent = filePath.getParent();
        if(!Files.exists(parent)){
            Files.createDirectories(parent);
        }
        if(!Files.exists(filePath)){
            Files.createFile(filePath);
        }
        File file = filePath.toFile();
        try(
                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                WritableByteChannel writableByteChannel = Channels.newChannel(bos)
        ){
            ByteBuffer buffer = ByteBuffer.wrap(bytes);
            writableByteChannel.write(buffer);
            buffer.clear();
        }
    }

    public static void main(String[] args) {
        File file = new File("D:\\xcwl\\picture", "test.jpg");
        try {
            final FileInputStream fileInputStream = new FileInputStream(file);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedInputStream.close();
            fileInputStream.close();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}
